
#include "delegate.h"

#include <QPainter>
#include <QSpinBox>
#include <QToolButton>
#include <QVariant>
#include <QIcon>
//! [0]
Delegate::Delegate(QObject *parent)
    : QStyledItemDelegate(parent)
{

}
//! [0]


//! [3]
void Delegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
    spinBox->interpretText();
    int value = spinBox->value();

    model->setData(index, value, Qt::EditRole);
}
//! [3]

//! [4]
void Delegate::updateEditorGeometry(QWidget *editor,
                                           const QStyleOptionViewItem &option,
                                           const QModelIndex &/* index */) const
{
    editor->setGeometry(option.rect);
}

void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.isValid()) {
        painter->save();
        QVariant var = index.data(Qt::UserRole+1);
        int type = var.toInt();

        // item 矩形区域
        QRectF rect;
        rect.setX(option.rect.x());
        rect.setY(option.rect.y());
        rect.setWidth(option.rect.width()-1);
        rect.setHeight(option.rect.height()-1);


        // 鼠标悬停或者选中时改变背景色
        if (option.state.testFlag(QStyle::State_MouseOver)) {
            painter->setPen(QPen(QColor("#ebeced")));
            painter->setBrush(QColor("#ebeced"));

        }
        if (option.state.testFlag(QStyle::State_Selected)) {
            painter->setPen(QPen(QColor("#e3e3e5")));
            painter->setBrush(QColor("#e3e3e5"));

        }
        painter->drawRect(option.rect);

        // 绘制图片，歌手，数量位置区域
        QRectF iconRect = QRectF(rect.adjusted(30,10,-30,-50));
        QRectF textRect = QRect(rect.x(),rect.y()+160,rect.width(),30);

        QIcon icon(index.data(Qt::DecorationRole).value<QIcon>());
        QPixmap pix(icon.pixmap(QSize(iconRect.width(),iconRect.height())));
        painter->drawPixmap(iconRect.x(),iconRect.y(), pix);
        painter->setPen(QPen(Qt::black));
        painter->setFont(QFont("Microsoft Yahei", 10));
        painter->drawText(textRect, Qt::AlignCenter,  index.data(Qt::DisplayRole).toString());


        painter->restore();
    }

}


//! [4]
